package com.example.springboot_jap_model.service.Impl;

import com.example.springboot_jap_model.constant.Constant;
import com.example.springboot_jap_model.dao.*;
import com.example.springboot_jap_model.domain.*;
import com.example.springboot_jap_model.domain.dto.UserDto;
import com.example.springboot_jap_model.enums.RespEntityEnum;
import com.example.springboot_jap_model.service.UserService;
import com.example.springboot_jap_model.utils.*;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.aspectj.apache.bcel.classfile.Code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.util.ListUtils;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.example.springboot_jap_model.enums.RespEntityEnum.PARAMETER_EXCEPTION;


@Service
public class UserServiceImpl implements UserService {

    private final static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleAndAuthorityDao roleAndAuthorityDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserAndRoleDao userAndRoleDao;
    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private HttpSession httpSession;

    @Override
    public RespEntity doLogin(User user) {
        if (ParameterCheckUtils.userCheck(user)) {
            logger.info("登录用户:{},{}", user.getUserName(), user.getPassWord());
            List<User> userList = userDao.findByUserNameAndStatus(user.getUserName(), Constant.SUCCESS_STATIC);
            if (ListUtils.isEmpty(userList)) {
                logger.error("账户不存在");
                return RespEntityUtils.error(RespEntityEnum.NOT_EXIST);
            } else {
                //当前存在 时刻 比较 密码
                MD5 md5 = new MD5();
                if (userList.get(0).getPassWord().equals(md5.getMD5ofStr(user.getPassWord()))) {
                    //登录 成功 存入 session
                    logger.info("用户登录成功:{}", user.getUserName());
                    httpSession.setAttribute(Constant.SESSION_LOGIN, userList.get(0));
                    return RespEntityUtils.success(RespEntityEnum.SUCCESS);
                } else {
                    //登录 失败
                    logger.error("密码错误!");
                    return RespEntityUtils.error(RespEntityEnum.U_OR_P_ERROR);//用户名密码错误
                }
            }
        }
        logger.error("提交参数异常");
        return RespEntityUtils.error(PARAMETER_EXCEPTION);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public RespEntity doLogOut() {
        //退出登录 清空 session 和 session 中 关于权限 的内容
        httpSession.removeAttribute(Constant.SESSION_LOGIN);
        httpSession.removeAttribute(Constant.SESSION_AUTO);
        return RespEntityUtils.success(RespEntityEnum.SUCCESS);
    }

    /**
     * 根据 用户状态查询 用户 除Admin账户外
     * 限制状态 和
     *
     * @param status //用户状态
     * @return
     */
    @Override
    public List<User> findUserByStatus(Integer status) {
        logger.info("查询用户：status--->{}", status);
        if (Constant.SUCCESS_STATIC == status || Constant.ERROR_STATIC == status) {
            return userDao.findByStatusAndType(status, Constant.PT_USER_TYPE);
        } else {
            return userDao.findByType(Constant.PT_USER_TYPE);
        }
    }

    @Override
    public RespEntity updateAuto(String authId) {
        User user = (User) httpSession.getAttribute(Constant.SESSION_LOGIN);
        if (user.getType() != Constant.GL_USER_TYPE) {
            return RespEntityUtils.error(RespEntityEnum.AUTO_FILTER);
        }
        //获取 串  并 查询 得到 authlist
        //删除 old user And role
        //新建 user and role
        //新建 role and auth
        Long[] ints = StringUtil.interception(authId);
        if (ints != null && ints.length > 0) {
            List<UserAndRole> userAndRoleOldList = userAndRoleDao.findByUserId(user.getId());
            if (!ListUtils.isEmpty(userAndRoleOldList)) {
                userAndRoleDao.deleteAll(userAndRoleOldList);
            }
            //authorityDao.findAllById(ints);
            //新建一个 role
            Role role = new Role();
            role.setAddTime(new Date());
            role.setName(user.getUserName());
            Role role1 = roleDao.save(role);
           /* //创建 role and auth
            List<RoleAndAuthority> roleAndAuthorityList = new ArrayList<>();
            for (Long integer : ints) {
                RoleAndAuthority roleAndAuthority = new RoleAndAuthority();
                roleAndAuthority.setRoleId(role1.getId());
                roleAndAuthority.setAuthId(integer);
                roleAndAuthorityList.add(roleAndAuthority);
            }
            if (!ListUtils.isEmpty(roleAndAuthorityList)) {
                roleAndAuthorityDao.saveAll(roleAndAuthorityList);
            }*/
            //创建 user and role
            UserAndRole userAndRole = new UserAndRole();
            userAndRole.setRoleId(role1.getId());
            userAndRole.setUserId(user.getId());
            userAndRoleDao.save(userAndRole);
            return RespEntityUtils.success(RespEntityEnum.SUCCESS);
        }
        return RespEntityUtils.error(PARAMETER_EXCEPTION);
    }

    @Override
    public List findAutoByUserIdAndUrl(Long userId, String url) {
        return userDao.findAutoByUserIdAndUrl(userId, url);
    }

    @Override
    public List<Authority> findAllAuthByUrl(String url) {
        return authorityDao.findByUrl(url);
    }

    @Override
    public List<Authority> findAllAuth() {
        return authorityDao.findAll();
    }

    @Override
    public RespEntity addAuth(Authority authority) {
        if (!ParameterCheckUtils.authCheck(authority)) {
            return RespEntityUtils.error(PARAMETER_EXCEPTION);
        }
        User user = (User) httpSession.getAttribute(Constant.SESSION_LOGIN);
        if (user.getType() == Constant.GL_USER_TYPE) {
            //管理员 才能添加
            //判断 是否存在
           /* List<Authority> authorityList = authorityDao.findByUrl(authority.getUrl());
            if (!ListUtils.isEmpty(authorityList)) {
                //有且 仅有一个
                Authority authority1 = authorityList.get(0);
                authority1.setName(authority.getName());
                authorityDao.save(authority1);
            } else {
                authorityDao.save(authority);
            }*/
            return RespEntityUtils.success(RespEntityEnum.SUCCESS);
        }
        return RespEntityUtils.error(RespEntityEnum.AUTO_FILTER);
    }

    @Override
    public RespEntity distributionAuth() {
        //获取 全部权限  并分配 给 管理员
        User user = (User) httpSession.getAttribute(Constant.SESSION_LOGIN);
        List<Authority> authorityList = authorityDao.findAll();
        Role role = new Role();
        role.setAddTime(new Date());
        role.setName(user.getUserName());
        Role role1 = roleDao.save(role);
        //创建 role and auth
        List<RoleAndAuthority> roleAndAuthorityList = new ArrayList<>();
        for (Authority authority : authorityList) {
            RoleAndAuthority roleAndAuthority = new RoleAndAuthority();
            roleAndAuthority.setRoleId(role1.getId());
            roleAndAuthority.setAuthId(authority.getId());
            roleAndAuthorityList.add(roleAndAuthority);
        }
        if (!ListUtils.isEmpty(roleAndAuthorityList)) {
            roleAndAuthorityDao.saveAll(roleAndAuthorityList);
        }
        //创建 user and role
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setRoleId(role1.getId());
        userAndRole.setUserId(user.getId());
        userAndRoleDao.save(userAndRole);

        return RespEntityUtils.success(RespEntityEnum.SUCCESS);
    }

    /**
     * 1.分页查询所有的用户
     * @param type
     * @param status
     * @param page
     * @return
     */
    @Override
    public RespEntity findByTypeAndStatus(Integer type, Integer status, int page) {
        Page<User> userPage = userDao.findByTypeAndStatus(type,status, PageableUtils.getPageable(page));
        List<UserDto> userDtoList = new ArrayList<>();
        for (User user : userPage.getContent()){
            userDtoList.add(new UserDto(user.getId(),user.getUserName(),user.getRealName(),user.getType(),user.getStatus(),user.getAddTime(),user.getLostLoinTime()));
        }
        return RespEntityUtils.success(userDtoList);
    }


    /**
     * 1.校验 用户名 是否存在
     *
     * @param user
     * @return
     */
    @Override
    public RespEntity addUser(User user) {
        //参数校验
        if (ParameterCheckUtils.userCheck(user)) {
            //查询 用户状态 是正常状态的用户 并允许登录操作
            List<User> userList = userDao.findByUserNameAndStatus(user.getUserName(), Constant.SUCCESS_STATIC);
            if (!ListUtils.isEmpty(userList)) {
                return RespEntityUtils.error(RespEntityEnum.USER_NAME_NOT_UNIQUE);
            }
            //md5 密码加密
            MD5 md5 = new MD5();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            user.setPassWord(md5.getMD5ofStr(user.getPassWord()));
            user.setStatus(Constant.SUCCESS_STATIC);
            user.setType(Constant.PT_USER_TYPE);
            user.setAddTime(new Date());
            user.setLostLoinTime(sdf.format(new Date()));
            userDao.save(user);
            return RespEntityUtils.success(RespEntityEnum.SUCCESS);
        }
        return RespEntityUtils.error(PARAMETER_EXCEPTION);
    }


}
